// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const axios = require('axios');
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event);
  const code = event.code.code;
  const appid = 'wx8a5b19e4aa3b5500';
  const secret = '084945bbf37afc298695ac2001b56275';
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
  try {
    let aut = event.user.user.aut
    let text = aut+event.text
    const res = await axios.get(url);
    const openid = res.data.openid;
    const session_key = res.data.session_key;
    console.log("openid:", openid);
    console.log("session_key:", session_key);
    //获取提醒的openid
    let cp = await db.collection('users').doc(event.user.user.cpid).get()
    console.log(cp);
debugger
    const result = await cloud.openapi.subscribeMessage.send({
      "touser": cp.data.openid,
      "page": 'pages/zhuye/index',
      "lang": 'zh_CN',
      "data": {
        "thing2": {
          "value": aut
        },
        "thing1": {
          "value": text
        },
        "time3": {
          "value": text
        },
      },
      "templateId": 'kC-NoxMdiSMZWexpw72En9bxx41uoDp1g1NrORXfc-w',
      "miniprogramState": 'trial'
    })} catch (err) {
      console.log(err);
      return{faals:false}
    }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}